package utils

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// R
// Code 0:ok 1, error
// Msg 操作成功 / 操作失败
// data null / data
type R struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func SuccessR(ctx *gin.Context, data interface{}, msg string) {
	if msg == "" {
		msg = "成功"
	}
	ctx.JSON(http.StatusOK, R{
		Code: 1,
		Msg:  msg,
		Data: data,
	})
}

func ErrorR(ctx *gin.Context, msg string) {
	if msg == "" {
		msg = "失败"
	}
	ctx.JSON(http.StatusOK, R{
		Code: -1,
		Msg:  msg,
		Data: nil,
	})
}

func CustomErrR(ctx *gin.Context, statusCode int, err error) {
	ctx.JSON(statusCode, R{
		Code: -1,
		Msg:  err.Error(),
		Data: nil,
	})
}

func ServerError(ctx *gin.Context, err error) {
	ctx.JSON(http.StatusInternalServerError, R{
		Code: -1,
		Msg:  err.Error(),
		Data: nil,
	})
}

func TokenFail(ctx *gin.Context) {
	CustomErrR(ctx, http.StatusUnauthorized, fmt.Errorf("登录授权失效"))
}
